<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">




<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/zhu/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/zhu/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/zhu/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/zhu/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/zhu/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/zhu/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/zhu/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="redis," />










<meta name="description" content="jedis 我们要使用Java来操作redis  jedis是官方推荐的的java连接开发工具，使用java操作redis中间件，如果你要使用java来操作redis，那么一定要对jedis十分熟悉  知其然，知其所以然">
<meta property="og:type" content="article">
<meta property="og:title" content="redis(2)">
<meta property="og:url" content="https://gitee-zct.gitee.io/zhu/2021-04-18/redis(2)/index.html">
<meta property="og:site_name" content="zhu">
<meta property="og:description" content="jedis 我们要使用Java来操作redis  jedis是官方推荐的的java连接开发工具，使用java操作redis中间件，如果你要使用java来操作redis，那么一定要对jedis十分熟悉  知其然，知其所以然">
<meta property="og:locale">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-114430-0803.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-144624-0502.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-173121-0288.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-170424-0218.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-172943-0440.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-175344-0559.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-170848-0824.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200924215943362.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200924215952210.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpc2VuMDEwNzAxMDc=,size_16,color_FFFFFF,t_70#pic_center">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-174552-0943.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-180603-0891.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-185304-0619.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-183011-0697.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-182913-0492.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-181259-0553.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-181740-0755.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-183751-0880.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-191809-0758.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-190212-0714.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-195413-0125.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-201151-0334.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-224700-0501.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210418-000640-0022.png">
<meta property="og:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210418-000152-0633.png">
<meta property="article:published_time" content="2021-04-17T16:56:16.363Z">
<meta property="article:modified_time" content="2021-04-17T17:00:41.037Z">
<meta property="article:author" content="zhu">
<meta property="article:tag" content="redis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-114430-0803.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee-zct.gitee.io/zhu/2021-04-18/redis(2)/"/>





  <title>redis(2) | zhu</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>


    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/zhu/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zhu</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">我的小世界</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/zhu/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/zhu/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/zhu/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/zhu/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/zhu/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/zhu/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://gitee-zct.gitee.io/zhu/zhu/2021-04-18/redis(2)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/zhu/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zhu">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">redis(2)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-04-18T00:56:16+08:00">
                2021-04-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/zhu/categories/%E5%AD%A6%E4%B9%A0/" itemprop="url" rel="index">
                    <span itemprop="name">学习</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  8.2k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  32
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="jedis"><a href="#jedis" class="headerlink" title="jedis"></a>jedis</h1><hr>
<p>我们要使用Java来操作redis</p>
<blockquote>
<p><font color='cornflowerblue'>jedis是官方推荐的的java连接开发工具，使用java操作redis中间件，如果你要使用java来操作redis，那么一定要对jedis十分熟悉</font></p>
</blockquote>
<p>知其然，知其所以然</p>
<p><em><span id="more"></span></em></p>
<p>学习不能急躁，慢慢来会很快。</p>
<p><font color='orange'>测试：</font></p>
<ol>
<li><p>导入对应的依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>redis.clients<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jedis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.2.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.alibaba<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>fastjson<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2.62<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></li>
<li><p>编码测试</p>
<ul>
<li>连接数据库</li>
<li>操作命令</li>
<li>断开连接</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> redis.clients.jedis.Jedis;  </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//1. new jedis对象即可</span></span><br><span class="line">        Jedis jedis = <span class="keyword">new</span> Jedis(<span class="string">&quot;47.111.157.72&quot;</span>,<span class="number">6379</span>);</span><br><span class="line">        <span class="comment">//jedis的所有命令就是我们之前学的所有指令</span></span><br><span class="line">        System.out.println(jedis.ping());        </span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">PONG</span><br></pre></td></tr></table></figure>





<h2 id="常用api"><a href="#常用api" class="headerlink" title="常用api"></a>常用api</h2><ul>
<li>String</li>
<li>List</li>
<li>Set</li>
<li>Hash</li>
<li>Zset</li>
</ul>
<p>所有的api命令，就是我们对应的上面学习的指令，一个都没有变化！</p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-114430-0803.png"></p>
</li>
</ol>
<blockquote>
<p><font color='orange'>事务</font></p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.jedis;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.alibaba.fastjson.JSONObject;</span><br><span class="line"><span class="keyword">import</span> redis.clients.jedis.Jedis;</span><br><span class="line"><span class="keyword">import</span> redis.clients.jedis.Transaction;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestTx</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Jedis jedis = <span class="keyword">new</span> Jedis(<span class="string">&quot;47.111.157.72&quot;</span>, <span class="number">6379</span>);</span><br><span class="line">        jedis.flushDB();</span><br><span class="line">        JSONObject jsonObject=<span class="keyword">new</span> JSONObject();</span><br><span class="line">        jsonObject.put(<span class="string">&quot;hello&quot;</span>,<span class="string">&quot;world&quot;</span>);</span><br><span class="line">        jsonObject.put(<span class="string">&quot;name&quot;</span>,<span class="string">&quot;zhu&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//开启事务</span></span><br><span class="line">        Transaction multi = jedis.multi();</span><br><span class="line">        String result = jsonObject.toJSONString();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            multi.set(<span class="string">&quot;user1&quot;</span>,result);</span><br><span class="line">            multi.set(<span class="string">&quot;user2&quot;</span>,result);</span><br><span class="line"></span><br><span class="line">            multi.exec();</span><br><span class="line">        &#125;<span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">            multi.discard();<span class="comment">//如果失败放弃事务</span></span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">//输出对应的值</span></span><br><span class="line">            System.out.println(jedis.get(<span class="string">&quot;user1&quot;</span>));</span><br><span class="line">            System.out.println(jedis.get(<span class="string">&quot;user2&quot;</span>));</span><br><span class="line">            jedis.close();<span class="comment">//关闭连接</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="springboot整合"><a href="#springboot整合" class="headerlink" title="springboot整合"></a>springboot整合</h1><p>Springboot操作数据：spring-data jpa jdbc mongodb redis</p>
<p>SpringData 也是和Springboot齐名的项目</p>
<p>说明：在springboot2.x之后，原来的jedis被替换成了lettuce</p>
<p>jedis:采用的是直连，多个线程操作不安全，如果想要避免不安全，使用redis pool 连接池  BIO模式</p>
<p>lettuce: 采用netty,实例可以在多个线程共享，不存在线程不安全的情况,可以减少线程数据，更像BIO模式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="meta">@ConditionalOnMissingBean(name = &quot;redisTemplate&quot;)</span> <span class="comment">// 我们可以自己定义一个redisTemplate来替换这个默认的！</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> RedisTemplate&lt;Object, Object&gt; <span class="title">redisTemplate</span><span class="params">(RedisConnectionFactory redisConnectionFactory)</span></span></span><br><span class="line"><span class="function">    <span class="keyword">throws</span> UnknownHostException </span>&#123;</span><br><span class="line">    <span class="comment">// 默认的 RedisTemplate 没有过多的设置，redis 对象都是需要序列化！</span></span><br><span class="line">    <span class="comment">// 两个泛型都是 Object, Object 的类型，我们后使用需要强制转换 &lt;String, Object&gt;</span></span><br><span class="line">    RedisTemplate&lt;Object, Object&gt; template = <span class="keyword">new</span> RedisTemplate&lt;&gt;();</span><br><span class="line">    template.setConnectionFactory(redisConnectionFactory);</span><br><span class="line">    <span class="keyword">return</span> template;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="meta">@ConditionalOnMissingBean</span> <span class="comment">//由于String是redis中最常使用的类型，所以说单独提出来了一 个bean！</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> StringRedisTemplate <span class="title">stringRedisTemplate</span><span class="params">(RedisConnectionFactory redisConnectionFactory)</span></span></span><br><span class="line"><span class="function">    <span class="keyword">throws</span> UnknownHostException </span>&#123;</span><br><span class="line">    StringRedisTemplate template = <span class="keyword">new</span> StringRedisTemplate();</span><br><span class="line">    template.setConnectionFactory(redisConnectionFactory);</span><br><span class="line">    <span class="keyword">return</span> template;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<blockquote>
<p><font color='red'>整合测试一下</font></p>
</blockquote>
<ul>
<li>导入依赖</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">         <span class="comment">&lt;!--操作redis--&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>配置连接</li>
</ul>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#springboot所有的配置类都是一个自动配置类 RedisAutoConfiguration</span></span><br><span class="line"><span class="comment">#自动配置类会绑定一个properties配置文件  RedisProperties</span></span><br><span class="line"></span><br><span class="line"><span class="meta">spring.redis.host</span>=<span class="string">47.111.157.72</span></span><br><span class="line"><span class="meta">spring.redis.port</span>=<span class="string">6379</span></span><br></pre></td></tr></table></figure>

<ul>
<li>测试</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.zhu;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.junit.jupiter.api.Test;</span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.test.context.SpringBootTest;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.connection.RedisConnection;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.RedisTemplate;</span><br><span class="line"></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Redis02SpringbootApplicationTests</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RedisTemplate redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">contextLoads</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//redisTemplate          操作不同的数据类型,</span></span><br><span class="line">        <span class="comment">// posForValue操作字符串 类似String</span></span><br><span class="line">        <span class="comment">//opsForList 操作List    类似List</span></span><br><span class="line">        <span class="comment">//opsForSet 操作Set    类似Set</span></span><br><span class="line"></span><br><span class="line">       <span class="comment">// 在企业开发中，80%情况下，都不会这种原生的方式去编写代码,编写RedisUtils</span></span><br><span class="line">        redisTemplate.opsForValue().set(<span class="string">&quot;mykey&quot;</span>,<span class="string">&quot;zhu&quot;</span>);</span><br><span class="line">        System.out.println(redisTemplate.opsForValue().get(<span class="string">&quot;mykey&quot;</span>));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//除了基本的操作,常用的方法都可以直接redisTemplate操作,比如事务和基本的增删改查</span></span><br><span class="line"><span class="comment">//        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();</span></span><br><span class="line"><span class="comment">//        connection.flushDb();</span></span><br><span class="line"><span class="comment">//        connection.flushAll();</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-144624-0502.png"></p>
<p>关于对象的保存</p>
<p>需要序列化,如果使用默认的序列化👇，会有在键里有转义字符，因为是默认jdk的序列化</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> age;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>于是，我们自己写配置类，来自定义序列化的方式👇</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.zhu.config;</span><br><span class="line"><span class="comment">//http://www.manongjc.com/detail/19-mcbchvzpiihmrlj.htmlpackage com.zhu.config;</span></span><br><span class="line"><span class="keyword">import</span> org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.connection.RedisConnectionFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.RedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.serializer.StringRedisSerializer;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@ConditionalOnMissingBean(name = &quot;redisTemplate&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RedisTemplate&lt;Object, Object&gt; <span class="title">redisTemplate</span><span class="params">(RedisConnectionFactory redisConnectionFactory)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        RedisTemplate&lt;Object, Object&gt; template = <span class="keyword">new</span> RedisTemplate&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//使用fastjson序列化</span></span><br><span class="line">        Jackson2JsonRedisSerializer&lt;Object&gt; fastJsonRedisSerializer = <span class="keyword">new</span> Jackson2JsonRedisSerializer&lt;Object&gt;(Object.class);</span><br><span class="line">        <span class="comment">//value的序列化采用fastJsonRedisSerializer</span></span><br><span class="line">        template.setValueSerializer(fastJsonRedisSerializer);</span><br><span class="line">        template.setHashValueSerializer(fastJsonRedisSerializer);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//key的序列化采用StringRedisSerializer</span></span><br><span class="line">        template.setKeySerializer(<span class="keyword">new</span> StringRedisSerializer());</span><br><span class="line">        template.setHashKeySerializer(<span class="keyword">new</span> StringRedisSerializer());</span><br><span class="line"></span><br><span class="line">        template.setConnectionFactory(redisConnectionFactory);</span><br><span class="line">        <span class="keyword">return</span> template;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>







<h2 id="redisUtils-amp-redisConfig工具类"><a href="#redisUtils-amp-redisConfig工具类" class="headerlink" title="redisUtils &amp; redisConfig工具类"></a><font color='cornflowerblue'>redisUtils &amp; redisConfig工具类</font></h2><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/kong240524885/article/details/115255340">https://blog.csdn.net/kong240524885/article/details/115255340</a></p>
<p><font color='orange'>所有redis操作，对于开发人员不难，但是更重要的是思想和每一种数据结构的用处和作用场景</font></p>
<p>P28 老师有些地方讲错了，并且错的有点多，1.他那样直接修改配置文件估计得重启才会有效，我和他一样得方式修改重启后才生效，如果通过客服端直接修改可能可以直接生效（这个没试验过），2.老师set5个键值对的时候，生成得rdb文件其实不是因为修改了才生成，应该是由save生成的，save其实也能生成rbd文件，只不过不是由子进程生成，而是直接由服务器生成，关于这点书上有说。3.flushdb本省其实是不会生成rdb文件的，他那样之所以生成rdb文件是因为满足了配置文件中多长时间修改了多少键的条件，关于这点可以先flushdb，然后删掉rdb文件，再flushdb，发现并不会生成rdb文件。</p>
<p>keep alive的描述是不是不准确<br>这里我不清楚，但是在http rest api测试中，<br>keep alive的意思是建立链接后，不中断链接，已知用这个链接发送请求，<br>如果是0，那么就是每次请求都会重新创建链接，请求结束后，断开链接，<br>这样性能其实是更慢，但更加符合真实多用户请求的场景。</p>
<p>感谢。</p>
<p>P29扩展<br>1、RDB持久化方式能够在指定的时间间隔内对你的数据进行快照存储。<br>2、AOF 持久化方式记录每次对服务器写的操作，当服务器重启的时候会重新执行这些命令来恢复原始的数据,，AOF命令以Redis协议追加保存每次写的操作到文件末尾，Redis还能对AOF文件进行后台重写，使得AOF文件的体积不至于过大。<br>3、只做缓存，如果你只希望你的数据在服务器运行的时候存在，你也可以不使用任何持久化<br>4、同时开启两种持久化方式<br>在这种情况下，当redis重启的时候会优先载入AOF文件来恢复原始的数据，因为在通常情况下AOF文件保存的数据集要比RDB文件保存的数据集要完整。<br>RDB的数据不实时，同时使用两者时服务器重启也只会找AOF文件，那要不要只使用AOF呢？作者建议不要，因为RDB更适合用于备份数据库( AOF在不断变化不好备份)，快速重启，而且不会有AOF可能潜在的Bug，留着作为一个万一的手段。<br>5、性能建议<br>因为RDB文件只用作后备用途，建议只在Slave上持久化RDB文件，而且只要15分钟备份一 次就够了，只保留 save 900 1 这条规则。<br>如果Enable AOF，好处是在最恶劣情况下也只会丢失不超过两秒数据，启动脚本较简单只load自己的AOF文件就可以了，代价一是带来了持续的IO，二是AOF rewrite的最后将rewrite过程中产生的新数据写到新文件造成的阻塞几乎是不可避免的。只要硬盘许可，应该尽量减少AOF rewrite的频率，AOF重写的基础大小默认值64M太小了，可以设到5G以上，默认超过原大小100%大小重写可以改到适当的数值。<br>如果不Enable AOF，仅靠Master-Slave Repllcation实现高可用性也可以，能省掉一大笔IO，也减少了rewrite时带来的系统波动。代价是如果Master/Slave 同时挂掉，会丢失 十几分钟的数据，启动脚本也要比较两个Master/Slave中的RDB文件，载入较新的那个，微博就是这种架构。</p>
<hr>
<h1 id="redis-conf-详解"><a href="#redis-conf-详解" class="headerlink" title="redis.conf 详解"></a>redis.conf 详解</h1><hr>
<p>启动就通过配置文件来启动的！</p>
<p><font color='orange'>单位</font></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 1k =&gt; 1000 bytes</span></span><br><span class="line"><span class="comment"># 1kb =&gt; 1024 bytes</span></span><br><span class="line"><span class="comment"># 1m =&gt; 1000000 bytes</span></span><br><span class="line"><span class="comment"># 1mb =&gt; 1024*1024 bytes</span></span><br><span class="line"><span class="comment"># 1g =&gt; 1000000000 bytes</span></span><br><span class="line"><span class="comment"># 1gb =&gt; 1024*1024*1024 bytes</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># units are case insensitive so 1GB 1Gb 1gB are all the same.</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ol>
<li>配置单位对大小写不敏感</li>
</ol>
<p><font color='orange'>包含</font></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">################################## INCLUDES ###################################</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Include one or more other config files here.  This is useful if you</span></span><br><span class="line"><span class="comment"># have a standard template that goes to all Redis servers but also need</span></span><br><span class="line"><span class="comment"># to customize a few per-server settings.  Include files can include</span></span><br><span class="line"><span class="comment"># other files, so use this wisely.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Note that option &quot;include&quot; won&#x27;t be rewritten by command &quot;CONFIG REWRITE&quot;</span></span><br><span class="line"><span class="comment"># from admin or Redis Sentinel. Since Redis always uses the last processed</span></span><br><span class="line"><span class="comment"># line as value of a configuration directive, you&#x27;d better put includes</span></span><br><span class="line"><span class="comment"># at the beginning of this file to avoid overwriting config change at runtime.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># If instead you are interested in using includes to override configuration</span></span><br><span class="line"><span class="comment"># options, it is better to use include as the last line.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># include /path/to/local.conf</span></span><br><span class="line"><span class="comment"># include /path/to/other.conf</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><font color='pink'>网络</font></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">bind</span> 0.0.0.0        <span class="comment">#绑定ip</span></span><br><span class="line">protected-mode yes  <span class="comment">#保护模式</span></span><br><span class="line">port 6379           <span class="comment">#端口设置</span></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<blockquote>
<p><font color='pink'>通用配置</font></p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">daemonize yes  <span class="comment">#开启守护进程的方式运行，默认是No,我们开启成yes</span></span><br><span class="line">pidfile /var/run/redis_6379.pid   <span class="comment">#如果以后台的方式运行，就需要指定pid进程文件</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Specify the server verbosity level.</span></span><br><span class="line"><span class="comment"># This can be one of:</span></span><br><span class="line"><span class="comment"># debug (a lot of information, useful for development/testing)</span></span><br><span class="line"><span class="comment"># verbose (many rarely useful info, but not a mess like the debug level)</span></span><br><span class="line"><span class="comment"># notice (moderately verbose, what you want in production probably)生产环境适合</span></span><br><span class="line"><span class="comment"># warning (only very important / critical messages are logged) 只打印关键信息</span></span><br><span class="line">loglevel notice</span><br><span class="line">logfile <span class="string">&quot;&quot;</span>          <span class="comment">#日志的文件名</span></span><br><span class="line">databases 16        <span class="comment">#数据库的数量，默认是16个数据库</span></span><br><span class="line"></span><br><span class="line">always-show-logo no <span class="comment">#是否总是显示logo</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p><font color='pink'>快照</font></p>
</blockquote>
<p>持久化，在规定时间内，执行了多少次操作，则会持久化到.rdb  </p>
<p>redis是内存数据库，如果没有持久化，断电数据就没了</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">#372行</span></span><br><span class="line"><span class="comment"># save 3600 1                 #如果3600秒内至少有1个修改，就继进行持久化操作</span></span><br><span class="line"><span class="comment"># save 300 100                # </span></span><br><span class="line"><span class="comment"># save 60 10000</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#我们之后学习持久化，会自己定义这个测试</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">stop-writes-on-bgsave-error yes  <span class="comment">#持久化出错了，数据库是否还会继续工作</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">rdbcompression yes               <span class="comment">#是否压缩rdb文件（持久化的文件，需要消耗cpu的资源）</span></span><br><span class="line"></span><br><span class="line">rdbchecksum yes                 <span class="comment">#保存rdb文件进行错误的检查校验</span></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">dir ./                         <span class="comment">#rdb文件保存的目录！</span></span><br><span class="line">  </span><br><span class="line"></span><br></pre></td></tr></table></figure>

<blockquote>
<p><font color='pink'>replication复制，后面讲解主从复制，会详解</font></p>
</blockquote>
<blockquote>
<p><font color='pink'> SECURITY</font></p>
</blockquote>
<p>在这里设置redis密码，默认没有</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">[root@izbp15hyph4achwhnnv8i5z ~]<span class="comment"># redis-cli</span></span><br><span class="line">127.0.0.1:6379&gt; config get requirepass</span><br><span class="line">1) <span class="string">&quot;requirepass&quot;</span></span><br><span class="line">2) <span class="string">&quot;&quot;</span></span><br><span class="line">127.0.0.1:6379&gt; config <span class="built_in">set</span> requirepass root</span><br><span class="line">OK</span><br><span class="line"></span><br><span class="line"><span class="comment"># ---重启---</span></span><br><span class="line"></span><br><span class="line">[root@izbp15hyph4achwhnnv8i5z ~]<span class="comment"># redis-cli</span></span><br><span class="line">127.0.0.1:6379&gt; config get requirepass</span><br><span class="line">(error) NOAUTH Authentication required.</span><br><span class="line">127.0.0.1:6379&gt; auth root</span><br><span class="line">OK</span><br><span class="line">127.0.0.1:6379&gt; config get requirepass</span><br><span class="line">1) <span class="string">&quot;requirepass&quot;</span></span><br><span class="line">2) <span class="string">&quot;root&quot;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>



<blockquote>
<p><font color='pink'>CLIENT</font></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">maxclients 10000     <span class="comment">#设置能连接客户端的最大数量</span></span><br><span class="line">maxmemory &lt;bytes&gt;   <span class="comment">#配置最大的内存容量</span></span><br><span class="line">maxmemory-policy noeviction <span class="comment">#内存达到上限，处理策略</span></span><br><span class="line"></span><br><span class="line">		maxmemory-policy 六种方式</span><br><span class="line">        1、volatile-lru：只对设置了过期时间的key进行LRU（默认值） </span><br><span class="line">        2、allkeys-lru ： 删除lru算法的key   </span><br><span class="line">        3、volatile-random：随机删除即将过期key   </span><br><span class="line">        4、allkeys-random：随机删除   </span><br><span class="line">        5、volatile-ttl ： 删除即将过期的   </span><br><span class="line">        6、noeviction ： 永不过期，返回错误</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<p>1225 <font color='pink'>APPEND ONLY MODE</font></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">appendonly no      <span class="comment">#默认不开启AOP,默认使用rdb持久化，在大部分情况下，rdb完全够用</span></span><br><span class="line"></span><br><span class="line">appendfilename <span class="string">&quot;appendonly.aof&quot;</span> <span class="comment">#持久化文件的名字</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># appendfsync always     #每次修改都会sync同步,.性能消耗</span></span><br><span class="line">appendfsync everysec     <span class="comment">#每秒执行一次，但是可能会丢失这 一秒的数据</span></span><br><span class="line"><span class="comment"># appendfsync no        #不执行sync,这时候操作系统自己同步数据，速度最快</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>具体在redis持久化那里</p>
</blockquote>
<p>工作中，一些小小的配置就可以优化可观性能。</p>
<h1 id="Redis持久化"><a href="#Redis持久化" class="headerlink" title="Redis持久化"></a>Redis持久化</h1><hr>
<p>面试和工作，持久化都是重点！<br>Redis 是内存数据库，如果不将内存中的数据库状态保存到磁盘，那么一旦服务器进程退出，服务器中<br>的数据库状态也会消失。所以 Redis 提供了持久化功能！</p>
<h2 id="RDB"><a href="#RDB" class="headerlink" title="RDB"></a>RDB</h2><blockquote>
<p><font color='orange'>什么是RDB</font></p>
</blockquote>
<img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-173121-0288.png" style="zoom: 80%;" />

<p>在指定的时间间隔内将内存中的数据集快照写入磁盘，也就是行话讲的Snapshot快照，它恢复时是将快照文件直接读到内存里。</p>
<p>Redis会单独创建（fork）一个子进程来进行持久化，会先将数据写入到一个临时文件中，待持久化过程都结束了，再用这个临时文件替换上次持久化好的文件。整个过程中，主进程是不进行任何IO操作的。这就确保了极高的性能。如果需要进行大规模数据的恢复，且对于数据恢复的完整性不是非常敏感，那RDB方式要比AOF方式更加的高效。RDB的缺点是最后一次持久化后的数据可能丢失。我们默认的就是RDB，一般情况下不需要修改这个配置！</p>
<p><font color='pink'>有时候在生产环境我们会将这个文件进行备份！</font>因为不备份丢失就没了</p>
<p><font color='cornflowerblue'>rdb保存的文件是dump.rdb</font> 都是在我们的配置文件中快照中进行配置的！</p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-170424-0218.png"></p>
<p>————————————————<br>版权声明：本文为CSDN博主「哦到凯呀」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。<br>原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/lisen01070107/article/details/108507798">https://blog.csdn.net/lisen01070107/article/details/108507798</a></p>
<blockquote>
<p><font color='orange'>触发机制</font></p>
</blockquote>
<ul>
<li>1、save的规则满足的情况下，会自动触发rdb规则</li>
<li>2、执行 flushall 命令，也会触发我们的rdb规则！</li>
<li>3、退出redis，也会产生 rdb 文件！</li>
</ul>
<p>备份完生成dump.rdb文件</p>
<blockquote>
<p><font color='orange'>如何恢复rdb文件</font></p>
</blockquote>
<ol>
<li><p>只需要将rdb文件放在我们启动目录的就可以了，redis启动的时候会自动坚持dump.rdb数据，恢复其中的数据</p>
</li>
<li><p>查看需要存放的位置</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; config get dir</span><br><span class="line">1) <span class="string">&quot;dir&quot;</span></span><br><span class="line">2) <span class="string">&quot;/usr/local/bin&quot;</span>  <span class="comment">#如果这个目录下存在dunp.rdb文件启动就会自动恢复其中的数据</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>几乎就他自己默认的配置就够用了，但是我们还是要去学习</p>
</blockquote>
<p>优点：</p>
<pre><code>1. 适合大规模的数据恢复！
2. 对数据的完整性要求不高！
</code></pre>
<p>缺点:</p>
<ol>
<li>需要一定的时间间隔进行操作！如果redis意外宕机，最后一次的修改信息就没有了</li>
<li>fork进程的时候会占用一点的内存空间。</li>
</ol>
</li>
</ol>
<h2 id="AOP"><a href="#AOP" class="headerlink" title="AOP"></a>AOP</h2><p>（Append Only File）</p>
<p>将我们的所有命令都记录下来，history，恢复的时候就把这个文件全部在执行一遍！</p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-172943-0440.png"></p>
<p>以日志的形式来记录每个写操作，将Redis执行过的所有指令记录下来（读操作不记录），只许追加文件但不可以改写文件，redis启动之初会读取该文件重新构建数据，换言之，redis重启的话就根据日志文件的内容将写指令从前到后执行一次以完成数据的恢复工作</p>
<blockquote>
<p><font color='orange'>Aof保存的是 appendonly.aof 文件</font></p>
</blockquote>
<p>快照功能（RDB）并不是非常耐久（durable）： 如果 Redis因为某些原因而造成故障停机，那么服务器将丢失最近写入、以及未保存到快照中的那些数据。 从 1.1 版本开始， Redis 增加了一种完全耐久的持久化方式： AOF 持久化。</p>
<blockquote>
<p><font color='orange'>什么是AOF</font></p>
</blockquote>
<p>快照功能（RDB）并不是非常耐久（durable）： 如果 Redis因为某些原因而造成故障停机，那么服务器将丢失最近写入、以及未保存到快照中的那些数据。 从 1.1 版本开始， Redis 增加了一种完全耐久的持久化方式： AOF 持久化。</p>
<p>如果要使用AOF，需要修改配置文件</p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-175344-0559.png"></p>
<p>appendonly no yes则表示启用AOF</p>
<p>默认是不开启的，我们需要手动配置，然后重启redis，就可以生效了！</p>
<p>如果这个aof文件有错位，这时候redis是启动不起来的，我需要修改这个aof文件</p>
<p>redis给我们提供了一个工具redis-check-aof –fix</p>
<blockquote>
<p>优缺点</p>
<p>appendonly yes  # 默认是不开启aof模式的，默认是使用rdb方式持久化的，在大部分的情况下，rdb完全够用<br>appendfilename “appendonly.aof”</p>
<p>appendfsync always # 每次修改都会sync 消耗性能</p>
<p>appendfsync everysec # 每秒执行一次 sync 可能会丢失这一秒的数据</p>
<p>appendfsync no # 不执行 sync ,这时候操作系统自己同步数据，速度最快</p>
</blockquote>
<p>不想学了。。。P29</p>
<h1 id="发布订阅"><a href="#发布订阅" class="headerlink" title="发布订阅"></a>发布订阅</h1><hr>
<p>Redis 发布订阅(pub/sub)是一种==消息通信模式==：发送者(pub)发送消息，订阅者(sub)接收消息。微信、微博、关注系统！<br>Redis 客户端可以订阅任意数量的频道。<br>订阅/发布消息图：<br>                第一个：消息发送者，<br>                第二个：频道<br>                第三个：消息订阅者！</p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-170848-0824.png"></p>
<p><img src="https://img-blog.csdnimg.cn/20200924215943362.png#pic_center"></p>
<p><img src="https://img-blog.csdnimg.cn/20200924215952210.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpc2VuMDEwNzAxMDc=,size_16,color_FFFFFF,t_70#pic_center"></p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-174552-0943.png"></p>
<blockquote>
<p><font color='orange'>测试</font></p>
<p>订阅端</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; subscribe zhu</span><br><span class="line">Reading messages... (press Ctrl-C to quit)</span><br><span class="line">1) <span class="string">&quot;subscribe&quot;</span></span><br><span class="line">2) <span class="string">&quot;zhu&quot;</span></span><br><span class="line">3) (<span class="built_in">integer</span>) 1</span><br><span class="line"><span class="comment">#等待读取推送的信息</span></span><br><span class="line">1) <span class="string">&quot;message&quot;</span>       <span class="comment">#消息 </span></span><br><span class="line">2) <span class="string">&quot;zhu&quot;</span>           <span class="comment">#哪个频道的消息</span></span><br><span class="line">3) <span class="string">&quot;hello,zhu&quot;</span>     <span class="comment">#消息的具体内容</span></span><br><span class="line"></span><br><span class="line">1) <span class="string">&quot;message&quot;</span>       <span class="comment">#消息 </span></span><br><span class="line">2) <span class="string">&quot;zhu&quot;</span>           <span class="comment">#哪个频道的消息</span></span><br><span class="line">3) <span class="string">&quot;hello,redis&quot;</span>   <span class="comment">#消息的具体内容</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>发送端</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; publish zhu hello,zhu   <span class="comment">#发布者发布消息</span></span><br><span class="line">(<span class="built_in">integer</span>) 1</span><br><span class="line">127.0.0.1:6379&gt; publish zhu hello,redis  <span class="comment">#发布者发布消息</span></span><br><span class="line">(<span class="built_in">integer</span>) 1</span><br></pre></td></tr></table></figure>
</blockquote>
<blockquote>
<p><font color='pink'>原理</font></p>
</blockquote>
<p>每个 Redis 服务器进程都维持着一个表示服务器状态的 redis.h/redisServer 结构， 结构的 pubsub_channels 属性是一个字典，==这个字典就用于保存订阅频道的信息==，其中，==字典的键为正在被订阅的频道， 而字典的值则是一个链表， 链表中保存了所有订阅这个频道的客户端。==<br><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-180603-0891.png"></p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-185304-0619.png"></p>
<p>使用场景：</p>
<ol>
<li>实时消息系统</li>
<li>实时聊天（频道当作聊天室，将信息回显给所有人）</li>
<li>订阅，关注系统</li>
</ol>
<p>==稍微复杂的常见就会使用 消息中间件实现(专业的)：MQ,kafka,rabbitMq，rocketMq==</p>
<h1 id="主从复制"><a href="#主从复制" class="headerlink" title="主从复制"></a>主从复制</h1><hr>
<blockquote>
<p><font color='orange'>概念</font></p>
<p>主从复制，是指将一台Redis服务器的数据，复制到其他的Redis服务器。前者称为主节点（Master/Leader）,后者称为从节点（Slave/Follower）， 数据的==复制是单向的！只能由主节点复制到从节点==（主节点以写为主、从节点以读为主）。</p>
<p>默认情况下，<font color='pink'>每台Redis服务器都是主节点</font>，一个主节点可以有0个或者多个从节点，但每个从节点只能由一个主节点。</p>
</blockquote>
<blockquote>
<p><font color='orange'>作用</font></p>
<ul>
<li>数据冗余：主从复制实现了数据的热备份，是持久化之外的一种数据冗余的方式。</li>
<li>故障恢复：当主节点故障时，从节点可以暂时替代主节点提供服务，是一种服务冗余的方式</li>
<li>负载均衡：在主从复制的基础上，配合读写分离，由主节点进行写操作，从节点进行读操作，分担服务器的负载；尤其是</li>
<li>读多写少的场景下，通过多个从节点分担负载，提高并发量。</li>
<li>高可用基石：主从复制还是哨兵和集群能够实施的基础。</li>
</ul>
</blockquote>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-183011-0697.png"></p>
<p>主从复制，读写分离，80%情况下都是进行读操作，减去服务器压力，架构中经常使用,==一主三从==,至少一主二从</p>
<p><font color='pink'>真实的项目中不可能单机,因为性能会有瓶颈.必须搭建集群.单台redis最大使用内存不应超过20G</font></p>
<img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-182913-0492.png" style="zoom:67%;" />

<blockquote>
<p><font color='orange'>为什么使用集群</font></p>
<ul>
<li>单台服务器难以负载大量的请求</li>
<li>单台服务器故障率高，系统崩坏概率大</li>
<li>单台服务器内存容量有限。</li>
</ul>
</blockquote>
<blockquote>
<p>环境配置</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">127.0.0.1:6379&gt; info replication         <span class="comment">#查看当前库的消息</span></span><br><span class="line"><span class="comment"># Replication</span></span><br><span class="line">role:master                              <span class="comment">#角色 master</span></span><br><span class="line">connected_slaves:0                       <span class="comment">#没有从机</span></span><br><span class="line">master_failover_state:no-failover</span><br><span class="line">master_replid:7fb316175bb77b584dd45dc70ff80413c176985d</span><br><span class="line">master_replid2:0000000000000000000000000000000000000000</span><br><span class="line">master_repl_offset:0</span><br><span class="line">second_repl_offset:-1</span><br><span class="line">repl_backlog_active:0</span><br><span class="line">repl_backlog_size:1048576</span><br><span class="line">repl_backlog_first_byte_offset:0</span><br><span class="line">repl_backlog_histlen:0</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>复制三个配置文件,修改对应信息</p>
<ol>
<li><p>port</p>
</li>
<li><p>pid名字</p>
</li>
<li><p>log文件名字</p>
</li>
<li><p>dump.rdb 名字</p>
</li>
</ol>
<p>修改完毕后启动三个redis服务器,可以通过查看</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">[root@izbp15hyph4achwhnnv8i5z bin]<span class="comment"># redis-server kconfig/redis79.conf </span></span><br><span class="line">[root@izbp15hyph4achwhnnv8i5z bin]<span class="comment"># ls</span></span><br><span class="line">6379.log  kconfig  redis-benchmark  redis-check-aof  redis-check-rdb  redis-cli  redis-sentinel  redis-server</span><br><span class="line">[root@izbp15hyph4achwhnnv8i5z bin]<span class="comment"># redis-server kconfig/redis80.conf </span></span><br><span class="line">[root@izbp15hyph4achwhnnv8i5z bin]<span class="comment"># ls</span></span><br><span class="line">6379.log  6380.log  kconfig  redis-benchmark  redis-check-aof  redis-check-rdb  redis-cli  redis-sentinel  redis-server</span><br><span class="line">[root@izbp15hyph4achwhnnv8i5z bin]<span class="comment"># redis-server kconfig/redis81.conf </span></span><br><span class="line">[root@izbp15hyph4achwhnnv8i5z bin]<span class="comment"># ls</span></span><br><span class="line">6379.log  6380.log  6381.log  kconfig  redis-benchmark  redis-check-aof  redis-check-rdb  redis-cli  redis-sentinel  redis-server</span><br></pre></td></tr></table></figure>



<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[root@izbp15hyph4achwhnnv8i5z bin]<span class="comment"># ps -ef | grep redis</span></span><br><span class="line">root      9513     1  0 18:19 ?        00:00:03 redis-server 0.0.0.0:6379</span><br><span class="line">root      9669     1  0 18:30 ?        00:00:00 redis-server 0.0.0.0:6380</span><br><span class="line">root      9676     1  0 18:30 ?        00:00:00 redis-server 0.0.0.0:6381</span><br><span class="line">root      9687  8963  0 18:30 pts/1    00:00:00 grep --color=auto redis</span><br><span class="line"></span><br></pre></td></tr></table></figure>





<h2 id="一主二从"><a href="#一主二从" class="headerlink" title="一主二从"></a>一主二从</h2><hr>
<p><font color='red'>默认每个开启后都是主节点</font>一般情况下只要配置从机</p>
<img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-181259-0553.png" style="zoom:67%;" />

<p>认老大! 一主(79)  二从(80,81)</p>
<blockquote>
<p><font color='orange'>slaveof</font></p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#从机6380</span></span><br><span class="line">127.0.0.1:6380&gt; slaveof 127.0.0.1 6379</span><br><span class="line">OK</span><br><span class="line">127.0.0.1:6380&gt; info replication</span><br><span class="line"><span class="comment"># Replication</span></span><br><span class="line">role:slave                <span class="comment">#从机</span></span><br><span class="line">master_host:127.0.0.1</span><br><span class="line">master_port:6379</span><br><span class="line">master_link_status:up</span><br><span class="line">master_last_io_seconds_ago:5</span><br><span class="line">master_sync_in_progress:0</span><br><span class="line">slave_repl_offset:14</span><br><span class="line">slave_priority:100</span><br><span class="line">slave_read_only:1</span><br><span class="line">connected_slaves:0</span><br><span class="line">master_failover_state:no-failover</span><br><span class="line">master_replid:22a65475a44b6f66fb0666230b85b4b5bc2104f8</span><br><span class="line">master_replid2:0000000000000000000000000000000000000000</span><br><span class="line">master_repl_offset:14</span><br><span class="line">second_repl_offset:-1</span><br><span class="line">repl_backlog_active:1</span><br><span class="line">repl_backlog_size:1048576</span><br><span class="line">repl_backlog_first_byte_offset:1</span><br><span class="line">repl_backlog_histlen:14</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 主机6379</span></span><br><span class="line">127.0.0.1:6379&gt; info replication</span><br><span class="line"><span class="comment"># Replication</span></span><br><span class="line">role:master                                                <span class="comment">#主机</span></span><br><span class="line">connected_slaves:1</span><br><span class="line">slave0:ip=127.0.0.1,port=6380,state=online,offset=98,lag=1  <span class="comment">#他的小弟</span></span><br><span class="line">master_failover_state:no-failover</span><br><span class="line">master_replid:22a65475a44b6f66fb0666230b85b4b5bc2104f8</span><br><span class="line">master_replid2:0000000000000000000000000000000000000000</span><br><span class="line">master_repl_offset:98</span><br><span class="line">second_repl_offset:-1</span><br><span class="line">repl_backlog_active:1</span><br><span class="line">repl_backlog_size:1048576</span><br><span class="line">repl_backlog_first_byte_offset:1</span><br><span class="line">repl_backlog_histlen:98</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>真实的主从配置,应该在配置文件中配置,这样就是永久的,我们这里使用的命令,就是暂时的!</p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-181740-0755.png"></p>
<blockquote>
<p><font color='yellow'>细节了解,主机可以设置值,从机只能读</font></p>
<p>主机的所有数据都会被从机保存</p>
</blockquote>
<blockquote>
<p>测试:主机断开连接,从机依旧连接到主机,但是没有写操作,如果主机回来了,从机依旧可以直接读取主机写的信息</p>
<p>保证高可用性.</p>
<p>如果是使用命令行配置的主从,如果从机重启,便变成主机了</p>
<p>只要变成从机,立马就从主机获取值(变成从机立马全量复制)</p>
</blockquote>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-183751-0880.png"></p>
<blockquote>
<p>层层链路,上一个主节点连接下一个主节点</p>
<p>这个时候也可以完成主从复制</p>
</blockquote>
<hr>
<blockquote>
<p><font color='green'>如果没有老大,这个时候能不能选择一个老大出来呢?</font></p>
<p>谋朝篡位     <font color='yellow'>slaveof no one</font></p>
<p>如果主机断开了连接,我们可以使用slaveof no one 使得自己变成主机,其他结点可以<font color='pink'>手动</font>连接到我,哨兵可以<font color='pink'>自动</font>选老大</p>
</blockquote>
<h2 id="哨兵模式"><a href="#哨兵模式" class="headerlink" title="哨兵模式"></a>哨兵模式</h2><hr>
<img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-191809-0758.png" style="zoom: 67%;" />



<p>实际业务多哨兵,层层监督</p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-190212-0714.png"></p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-195413-0125.png"></p>
<blockquote>
<p><font color='orange'>测试! </font></p>
</blockquote>
<p>目前的状态是一主二从</p>
<blockquote>
<ol>
<li>编写哨兵配置文件sentinel.conf</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sentinel monitor mymaster 127.0.0.1 6379 1</span><br></pre></td></tr></table></figure>

<ol start="2">
<li><p>启动哨兵</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">redis-sentinel kconfig&#x2F;sentinel.conf </span><br></pre></td></tr></table></figure>

<p>如果master结点断开,这个时候就会从从机中选择一个服务器(这里有一个投票算法),如果主机此时回来了只能归并到新的主机,当作从机.这就是哨兵模式</p>
</li>
</ol>
<blockquote>
<p>优点:</p>
<ol>
<li>哨兵集群,基于主从复制,所有主从配置优点,他都有</li>
<li>主从可以转移,故障可以转移,系统的可用性更好</li>
<li>哨兵模式就是主从模式的扩展,手动到自动,更加建健壮</li>
</ol>
<p>缺点:</p>
<ol>
<li>Redis不好在线扩容,集群容量到达上限,在线扩容十分麻烦</li>
<li>实现哨兵模式的配置其实是很麻烦的,里面有很多选择</li>
</ol>
</blockquote>
</blockquote>
<p><font color='red'>扩展</font></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line">1. 哨兵配置文件:sentinel.conf</span><br><span class="line"><span class="comment"># Example sentinel.conf</span></span><br><span class="line"> </span><br><span class="line"><span class="comment"># 哨兵sentinel实例运行的端口 默认26379；如果有哨兵集群，我们还需要配置每个哨兵的端口</span></span><br><span class="line">port 26379</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 哨兵sentinel的工作目录</span></span><br><span class="line">dir /tmp</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 哨兵sentinel监控的redis主节点的 ip port </span></span><br><span class="line"><span class="comment"># master-name  可以自己命名的主节点名字 只能由字母A-z、数字0-9 、这三个字符&quot;.-_&quot;组成。</span></span><br><span class="line"><span class="comment"># quorum 当这些quorum个数sentinel哨兵认为master主节点失联 那么这时 客观上认为主节点失联了</span></span><br><span class="line"><span class="comment"># sentinel monitor &lt;master-name&gt; &lt;ip&gt; &lt;redis-port&gt; &lt;quorum&gt;</span></span><br><span class="line">sentinel monitor mymaster 127.0.0.1 6379 1 <span class="comment"># 1 表示判定客观下线票数临界点</span></span><br><span class="line"> </span><br><span class="line"><span class="comment"># 当在Redis实例中开启了requirepass foobared 授权密码 这样所有连接Redis实例的客户端都要提供密码</span></span><br><span class="line"><span class="comment"># 设置哨兵sentinel 连接主从的密码 注意必须为主从设置一样的验证密码</span></span><br><span class="line"><span class="comment"># sentinel auth-pass &lt;master-name&gt; &lt;password&gt;</span></span><br><span class="line">sentinel auth-pass mymaster MySUPER--secret-0123passw0rd</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="comment"># 指定多少毫秒之后 主节点没有应答哨兵sentinel 此时 哨兵主观上认为主节点下线 默认30秒</span></span><br><span class="line"><span class="comment"># sentinel down-after-milliseconds &lt;master-name&gt; &lt;milliseconds&gt;</span></span><br><span class="line">sentinel down-after-milliseconds mymaster 30000</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 这个配置项指定了在发生failover主备切换时最多可以有多少个slave同时对新的master进行 同步，</span></span><br><span class="line"><span class="comment">#这个数字越小，完成failover所需的时间就越长，</span></span><br><span class="line"><span class="comment">#但是如果这个数字越大，就意味着越 多的slave因为replication而不可用。</span></span><br><span class="line"><span class="comment">#可以通过将这个值设为 1 来保证每次只有一个slave 处于不能处理命令请求的状态。</span></span><br><span class="line"><span class="comment"># sentinel parallel-syncs &lt;master-name&gt; &lt;numslaves&gt;</span></span><br><span class="line">sentinel parallel-syncs mymaster 1</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="comment"># 故障转移的超时时间 failover-timeout 可以用在以下这些方面： </span></span><br><span class="line"><span class="comment">#1. 同一个sentinel对同一个master两次failover之间的间隔时间。</span></span><br><span class="line"><span class="comment">#2. 当一个slave从一个错误的master那里同步数据开始计算时间。直到slave被纠正为向正确的master那里同步数据时。</span></span><br><span class="line"><span class="comment">#3.当想要取消一个正在进行的failover所需要的时间。  </span></span><br><span class="line"><span class="comment">#4.当进行failover时，配置所有slaves指向新的master所需的最大时间。不过，即使过了这个超时，slaves依然会被正确配置为指向master，但是就不按parallel-syncs所配置的规则来了</span></span><br><span class="line"><span class="comment"># 默认三分钟</span></span><br><span class="line"><span class="comment"># sentinel failover-timeout &lt;master-name&gt; &lt;milliseconds&gt;</span></span><br><span class="line">sentinel failover-timeout mymaster 180000</span><br><span class="line"> </span><br><span class="line"><span class="comment"># SCRIPTS EXECUTION</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">#配置当某一事件发生时所需要执行的脚本，可以通过脚本来通知管理员，例如当系统运行不正常时发邮件通知相关人员。</span></span><br><span class="line"><span class="comment">#对于脚本的运行结果有以下规则：</span></span><br><span class="line"><span class="comment">#若脚本执行后返回1，那么该脚本稍后将会被再次执行，重复次数目前默认为10</span></span><br><span class="line"><span class="comment">#若脚本执行后返回2，或者比2更高的一个返回值，脚本将不会重复执行。</span></span><br><span class="line"><span class="comment">#如果脚本在执行过程中由于收到系统中断信号被终止了，则同返回值为1时的行为相同。</span></span><br><span class="line"><span class="comment">#一个脚本的最大执行时间为60s，如果超过这个时间，脚本将会被一个SIGKILL信号终止，之后重新执行。</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">#通知型脚本:当sentinel有任何警告级别的事件发生时（比如说redis实例的主观失效和客观失效等等），将会去调用这个脚本，</span></span><br><span class="line"><span class="comment">#这时这个脚本应该通过邮件，SMS等方式去通知系统管理员关于系统不正常运行的信息。调用该脚本时，将传给脚本两个参数，</span></span><br><span class="line"><span class="comment">#一个是事件的类型，</span></span><br><span class="line"><span class="comment">#一个是事件的描述。</span></span><br><span class="line"><span class="comment">#如果sentinel.conf配置文件中配置了这个脚本路径，那么必须保证这个脚本存在于这个路径，并且是可执行的，否则sentinel无法正常启动成功。</span></span><br><span class="line"><span class="comment">#通知脚本</span></span><br><span class="line"><span class="comment"># sentinel notification-script &lt;master-name&gt; &lt;script-path&gt;</span></span><br><span class="line">  sentinel notification-script mymaster /var/redis/notify.sh</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 客户端重新配置主节点参数脚本</span></span><br><span class="line"><span class="comment"># 当一个master由于failover而发生改变时，这个脚本将会被调用，通知相关的客户端关于master地址已经发生改变的信息。</span></span><br><span class="line"><span class="comment"># 以下参数将会在调用脚本时传给脚本:</span></span><br><span class="line"><span class="comment"># &lt;master-name&gt; &lt;role&gt; &lt;state&gt; &lt;from-ip&gt; &lt;from-port&gt; &lt;to-ip&gt; &lt;to-port&gt;</span></span><br><span class="line"><span class="comment"># 目前&lt;state&gt;总是“failover”,</span></span><br><span class="line"><span class="comment"># &lt;role&gt;是“leader”或者“observer”中的一个。 </span></span><br><span class="line"><span class="comment"># 参数 from-ip, from-port, to-ip, to-port是用来和旧的master和新的master(即旧的slave)通信的</span></span><br><span class="line"><span class="comment"># 这个脚本应该是通用的，能被多次调用，不是针对性的。</span></span><br><span class="line"><span class="comment"># sentinel client-reconfig-script &lt;master-name&gt; &lt;script-path&gt;</span></span><br><span class="line"> sentinel client-reconfig-script mymaster /var/redis/reconfig.sh</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>初级饱和()</p>
<h1 id="Redis缓存穿透和雪崩"><a href="#Redis缓存穿透和雪崩" class="headerlink" title="Redis缓存穿透和雪崩"></a>Redis缓存穿透和雪崩</h1><p><strong>(面试高频工作常用)</strong></p>
<hr>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-201151-0334.png"></p>
<p>Redis缓存的使用,极大的提升了应用程序的性能和效率,特别是数据查询方面,但同时,他也带来了 一些问题,其中,最要害的问题,就是数据的一致性问题.从严格意义上说,这个问题无解.如果对数据的一致性要求很高,就不能使用缓存机制.</p>
<p>另外一些经典的问题就是,缓存穿透,缓存雪崩,和缓存击穿.目前,业界都有比较流行的解决方案.</p>
<blockquote>
<p><font color='yellow'>概念</font></p>
<p>缓存穿透的概念很简单，用户想要查询一个数据，发现redis内存数据库没有，也就是缓存没有命中，于是向持久层数据库查询。发现也没有，于是本次查询失败。当用户很多的时候，缓存都没有命中（秒杀！），于是都去请求了持久层数据库。这会给持久层数据库造成很大的压力，这时候就相当于出现了缓存穿透。洪水攻击。数据库也查不到就没有缓存，就会一直与数据库访问。</p>
</blockquote>
<blockquote>
<p><font color='yellow'>解决方案</font></p>
<h3 id="1-布隆过滤器"><a href="#1-布隆过滤器" class="headerlink" title="1.布隆过滤器"></a>1.布隆过滤器</h3><p>对所有可能查询的参数以Hash的形式存储，以便快速确定是否存在这个值，在控制层先进行拦截校验，校验不通过直接打回，减轻了存储系统的压力。</p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210417-224700-0501.png"></p>
<h3 id="2-缓存空对象"><a href="#2-缓存空对象" class="headerlink" title="2.缓存空对象"></a>2.缓存空对象</h3><p>一次请求若在缓存和数据库中都没找到，就在缓存中方一个空对象用于处理后续这个请求。</p>
<p><img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210418-000640-0022.png"></p>
<p>1、如果空值能够被缓存起来，这就意味着缓存需要更多的空间存储更多的键，因为这当中可能会有很多的空值的键；<br>2、即使对空值设置了过期时间，还是会存在缓存层和存储层的数据会有一段时间窗口的不一致，这对于需要保持一致性的业务会有影响</p>
</blockquote>
<h1 id="缓存击穿（量太大-缓存过期）"><a href="#缓存击穿（量太大-缓存过期）" class="headerlink" title="缓存击穿（量太大 缓存过期）"></a>缓存击穿（量太大 缓存过期）</h1><blockquote>
<p>==概述==</p>
<p>相较于缓存穿透，缓存击穿的目的性更强，一个存在的key，在缓存过期的一刻，同时有大量的请求，这些请求都会击穿到DB，造成瞬时DB请求量大、压力骤增。这就是缓存被击穿，只是针对其中某个key的缓存不可用而导致击穿，但是其他的key依然可以使用缓存响应。</p>
<p>比如热搜排行上，一个热点新闻被同时大量访问就可能导致缓存击穿。<br>==解决==</p>
<p>1.设置热点数据永不过期<br>这样就不会出现热点数据过期的情况，但是当Redis内存空间满的时候也会清理部分数据，而且此种方案会占用空间，一旦热点数据多了起来，就会占用部分空间。</p>
<p>2.加互斥锁(分布式锁)<br>在访问key之前，采用SETNX（set if not exists）来设置另一个短期key来锁住当前key的访问，访问结束再删除该短期key。保证同时刻只有一个线程访问。这样对锁的要求就十分高。</p>
</blockquote>
<h1 id="缓存雪崩"><a href="#缓存雪崩" class="headerlink" title="缓存雪崩"></a>缓存雪崩</h1><blockquote>
<p><font color='orange'>概念</font>：</p>
<p>大量的key设置了相同的过期时间，导致在缓存在同一时刻全部失效，造成瞬时DB请求量大、压力骤增，引起雪崩。</p>
<img src="https://gitee.com/gitee-zct/os/raw/master/pic/20210418-000152-0633.png" style="zoom:67%;" />

<p><font color='orange'>解决：</font></p>
<h3 id="redis高可用"><a href="#redis高可用" class="headerlink" title="redis高可用"></a>redis高可用</h3><p>这个思想的含义是，既然redis有可能挂掉，那我多增设几台redis，这样一台挂掉之后其他的还可以继续工作，其实就是==搭建的集群==</p>
<h3 id="限流降级（在springcloud讲过）"><a href="#限流降级（在springcloud讲过）" class="headerlink" title="限流降级（在springcloud讲过）"></a>限流降级（在springcloud讲过）</h3><p>这个解决方案的思想是，在缓存失效后，==通过加锁或者队列来控制读数据库写缓存的线程数量==。比如对某个key只允许一个线程查询数据和写缓存，其他线程等待。</p>
<h3 id="数据预热"><a href="#数据预热" class="headerlink" title="数据预热"></a>数据预热</h3><p>数据加热的含义就是在正式部署之前，我先把可能的数据先预先访问一遍，这样部分可能大量访问的数据就会加载到缓存中。在即将发生大并发访问前手动触发加载缓存不同的key，设置不同的过期时间，让缓存失效的时间点尽量均匀。</p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/zhu/tags/redis/" rel="tag"># redis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/zhu/2021-04-18/redis/" rel="next" title="redis(1)">
                <i class="fa fa-chevron-left"></i> redis(1)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/zhu/2021-04-21/1.%E4%BB%80%E4%B9%88%E6%98%AFJWT/" rel="prev" title="jwt">
                jwt <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/zhu/archives/">
              
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/zhu/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/zhu/tags/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#jedis"><span class="nav-number">1.</span> <span class="nav-text">jedis</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%B8%E7%94%A8api"><span class="nav-number">1.1.</span> <span class="nav-text">常用api</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#springboot%E6%95%B4%E5%90%88"><span class="nav-number">2.</span> <span class="nav-text">springboot整合</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#redisUtils-amp-redisConfig%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="nav-number">2.1.</span> <span class="nav-text">redisUtils &amp; redisConfig工具类</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#redis-conf-%E8%AF%A6%E8%A7%A3"><span class="nav-number">3.</span> <span class="nav-text">redis.conf 详解</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Redis%E6%8C%81%E4%B9%85%E5%8C%96"><span class="nav-number">4.</span> <span class="nav-text">Redis持久化</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#RDB"><span class="nav-number">4.1.</span> <span class="nav-text">RDB</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#AOP"><span class="nav-number">4.2.</span> <span class="nav-text">AOP</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85"><span class="nav-number">5.</span> <span class="nav-text">发布订阅</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%BB%E4%BB%8E%E5%A4%8D%E5%88%B6"><span class="nav-number">6.</span> <span class="nav-text">主从复制</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80%E4%B8%BB%E4%BA%8C%E4%BB%8E"><span class="nav-number">6.1.</span> <span class="nav-text">一主二从</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%93%A8%E5%85%B5%E6%A8%A1%E5%BC%8F"><span class="nav-number">6.2.</span> <span class="nav-text">哨兵模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Redis%E7%BC%93%E5%AD%98%E7%A9%BF%E9%80%8F%E5%92%8C%E9%9B%AA%E5%B4%A9"><span class="nav-number">7.</span> <span class="nav-text">Redis缓存穿透和雪崩</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E5%B8%83%E9%9A%86%E8%BF%87%E6%BB%A4%E5%99%A8"><span class="nav-number">7.0.1.</span> <span class="nav-text">1.布隆过滤器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E7%BC%93%E5%AD%98%E7%A9%BA%E5%AF%B9%E8%B1%A1"><span class="nav-number">7.0.2.</span> <span class="nav-text">2.缓存空对象</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%BC%93%E5%AD%98%E5%87%BB%E7%A9%BF%EF%BC%88%E9%87%8F%E5%A4%AA%E5%A4%A7-%E7%BC%93%E5%AD%98%E8%BF%87%E6%9C%9F%EF%BC%89"><span class="nav-number">8.</span> <span class="nav-text">缓存击穿（量太大 缓存过期）</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%BC%93%E5%AD%98%E9%9B%AA%E5%B4%A9"><span class="nav-number">9.</span> <span class="nav-text">缓存雪崩</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#redis%E9%AB%98%E5%8F%AF%E7%94%A8"><span class="nav-number">9.0.1.</span> <span class="nav-text">redis高可用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%99%90%E6%B5%81%E9%99%8D%E7%BA%A7%EF%BC%88%E5%9C%A8springcloud%E8%AE%B2%E8%BF%87%EF%BC%89"><span class="nav-number">9.0.2.</span> <span class="nav-text">限流降级（在springcloud讲过）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E9%A2%84%E7%83%AD"><span class="nav-number">9.0.3.</span> <span class="nav-text">数据预热</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhu</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">25.1k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





        
<div class="busuanzi-count">
 
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>


  
    <span class="site-uv">
      踩过的小伙伴
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      本站访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/zhu/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/zhu/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/zhu/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/zhu/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/zhu/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/zhu/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/zhu/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/zhu/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/zhu/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "./public/search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/zhu/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
